package cn.wolfcode.web.controller;


import cn.wolfcode.domain.Department;
import cn.wolfcode.queryobject.QueryObject;
import cn.wolfcode.resultpage.JsonResult;
import cn.wolfcode.service.IDepartmentService;
import cn.wolfcode.util.RequiredPermission;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/department")
public class DepartmentController {
    @Autowired
    private IDepartmentService departmentService;
    // 处理查询所有部门请求

   // @RequiredPermission(name="部门列表",expression="department:list")
    //@RequiresRoles("Market")
    // OR 满足一个条件就可以访问
    @RequiresPermissions(value = {"department:list","部门列表","department:delete","部门删除"},logical = Logical.OR)
    @RequestMapping("/list")
    public String list(Model model, QueryObject qo){
        // 调用分页查询的方法
        PageInfo<Department> resultPage = departmentService.query(qo);
        // 往模型存数据
        model.addAttribute("resultPage",resultPage);

        // 找视图
        return "department/list";
    }

    // 处理删除请求
    //@RequiredPermission(name="权限删除",expression="department:delete")
    @RequiresPermissions("department:delete")
    @RequiresRoles("HR_MGR")
    @RequestMapping("/delete")
    @ResponseBody
    public JsonResult delete(Long id){

            try {
                if (id != null)
                departmentService.delete(id);
                return new JsonResult();
            } catch (Exception e) {
                e.printStackTrace();
                // 告诉用户操作失败
                return new JsonResult(false,"操作失败");
            }
    }

    // 去新增或去修改页面
    @RequestMapping("/input")
    public String input(Long id,Model model){
      if(id != null){ // 表示去修改
          Department department = departmentService.selectOne(id);
          model.addAttribute("department",department);
      }
      return "department/input";
    }
    // 新增或修改
    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public JsonResult saveOrUpdate(Department dept) {

        try {
            if (dept.getId() != null){ // 修改
                departmentService.update(dept);
            }
            else {  // 新增
                departmentService.insert(dept);
            }
        } catch (Exception e) {
            e.printStackTrace();

            return new JsonResult(false,"操作失败");

        }
        return new JsonResult(true,"操作成功");
    }
}
